package socketHttpGet;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.InetAddress;


public class SocketGet
{
	private Socket yahoo;
	private PrintWriter pw;
	private final String searchStringFront = "<span id=\"yfs_l84_";
	private final String searchStringBack = "\">";
	
	public SocketGet ()
	{

	}
	
	private void sendGet (String symbol)
	{
		//doing the line ending manually because if ran on linux probably would
		//get different behavior.
		String getString = "GET /q?s="+symbol+" HTTP/1.0\r\n";
		pw.print(getString);
		pw.print("Host: finance.yahoo.com\r\n");
		pw.print("\r\n\r\n");
		
		this.pw.flush();
	}
	
	private double getPrice(String s, String currentSymbol)
	{
		String searchString = this.searchStringFront + currentSymbol + this.searchStringBack;
		int index = s.indexOf(searchString);
		
		if(index != -1)
		{
			String workingString = "";
			
			for(int i = index + searchString.length(); s.charAt(i) != '<' &&  i < s.length(); ++i)
			{
				if(s.charAt(i) != ',')
					workingString += s.charAt(i);
			}
			
			return Double.parseDouble(workingString);
		}
		
		return -1.0;
	}
	

	public double getQuote(String input) throws IOException
	{
		//next 2 should be locals and pass parameters, but i am too lazy to do that
		//but not too lazy to write this comment......
		this.yahoo = new Socket(InetAddress.getByName("finance.yahoo.com"), 80);
		this.pw = new PrintWriter(this.yahoo.getOutputStream());
		
		this.sendGet(input);
		
		byte[] buffer = new byte [1024];
		int numberRead;
		double returnVal = -1.0;
				
		BufferedInputStream bin;
		bin = new BufferedInputStream (this.yahoo.getInputStream());

		while (((numberRead = bin.read(buffer)) != -1) &&
				(returnVal == -1.0))
		{
			String readData = new String(buffer, 0, numberRead);
			returnVal = this.getPrice(readData, input);
		}
		
		bin.close();
		
		return returnVal;
	}

}
